<template>
  <div>
    <div class="container">
      <div class="container-menu">
        <ul>
          <li v-for="item in iconList" @click="setCanvasCursor(canvas, item)"><Icon :type="item.icon"></Icon></li>
        </ul>
      </div>
      <div class="container-canvas">
        <canvas id="canvas" width="800" height="600"></canvas>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      canvas: '',
      ctx: '',
      iconList: [
        { icon: 'edit', url: '/static/pencil.png', isImg: true },
        { icon: 'loop', url: '/static/eraser.png', isImg: true },
        { icon: 'eye-disabled', url: 'pointer', isImg: false }
      ],
      iconListIndex: ''
    }
  },
  watch: {},
  mounted () {
    this.createCanvas()
  },
  methods: {
    createCanvas () {
      this.canvas = document.getElementById('canvas')
      this.ctx = canvas.getContext('2d')
    },
    setCanvasCursor (el, row) {
      const _this = this
      switch (row.icon) {
        case 'eye-disabled':
          this.ctx.clearRect(20, 0, this.canvas.width, this.canvas.height)
          break
        default:
          console.log(row.url)
          el.onmouseover = function () {
            row.isImg ? this.style.cursor = 'url('+ row.url +'), auto' : this.style.cursor = row.url
            _this.mouseDown()
            _this.mouseUp()
          }
          this.iconListIndex = row.icon
          break
      }
     
    },
    
    mouseDown () {
      const _this = this
      this.canvas.onmousedown = function () {
        _this.mouseMove()
      }
    },
    mouseUp () {
      const _this = this
      this.canvas.onmouseup = function () {
        _this.canvas.onmousemove = null
      }
    },
    mouseMove (icon) {
      const _this = this
      this.ctx.beginPath()
      // this.ctx.moveTo(45, 45)
      this.canvas.onmousemove = function (event) {
        if (_this.iconListIndex === 'loop') {
          _this.ctx.clearRect(event.offsetX, event.offsetY, 25, 25)
        } else {
          _this.ctx.lineTo(event.offsetX, event.offsetY)
        }
        _this.ctx.stroke()
      }
    }
  }
}
</script>
<style lang="sass" scoped>
canvas 
  border: 2px solid red
.container
  display: flex
  .container-menu
    ul
      list-style: none
      li
        padding: 10px 20px
        background: #03a9f46e
        border-bottom: 1px solid #9e9e9e7a
        cursor: pointer
      li:hover
        background: #8bc34a
</style>

